﻿using System;
using System.Collections.Generic;
using WPF_CAD.Model;

namespace WPF_CAD.Algorithms
{
    public class BressenhamLine
    {
        public static IEnumerable<IPoint> GetLineRepresentation(IPoint begin, IPoint end)
        {
            var x0 = (int)begin.X;
            var y0 = (int)begin.Y;
            var x1 = (int)end.X;
            var y1 = (int)end.Y;
            var steep = Math.Abs(y1 - y0) > Math.Abs(x1 - x0);
            if (steep)
            {
                Swap(ref x0, ref y0);
                Swap(ref x1, ref y1);
                yield return new CustomPoint(y0, x0);
            }
            var deltax = Math.Abs(x1 - x0);
            var deltay = Math.Abs(y1 - y0);
            var error = 0;
            var x = x0;
            var y = y0;
            int xstep, ystep;
            if (x0 < x1)
                xstep = 1;
            else
                xstep = -1;
            if (y0 < y1)
                ystep = 1;
            else
                ystep = -1;
            while (x != x1)
            {
                x += xstep;
                error += deltay;
                if ((error) > deltax)
                {
                    y += ystep;
                    error -= deltax;
                }
                if (steep)
                {
                    yield return new CustomPoint(y, x);
                }
                else
                {
                    yield return new CustomPoint(x, y);
                }
            }
        }

        public static void Swap(ref int a, ref int b)
        {
            var tmp = a;
            a = b;
            b = tmp;
        }
    }
}
